package com.bnz.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bnz.common.utils.PageUtils;
import com.bnz.common.utils.Query;
import com.bnz.manager.dao.TypeTemplateDao;
import com.bnz.manager.entity.SpecificationOptionEntity;
import com.bnz.manager.entity.TypeTemplateEntity;
import com.bnz.manager.service.SpecificationOptionService;
import com.bnz.manager.service.TypeTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("typeTemplateService")
public class TypeTemplateServiceImpl extends ServiceImpl<TypeTemplateDao, TypeTemplateEntity> implements TypeTemplateService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SpecificationOptionService optionService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TypeTemplateEntity> page = this.page(
                new Query<TypeTemplateEntity>().getPage(params),
                new QueryWrapper<TypeTemplateEntity>()
        );

        return new PageUtils(page);
    }
    /**
     * @author: zhanghao
     * @date: 2023/3/7 16:17
     * @param: []
     * @return: java.util.List<com.bnz.manager.entity.TypeTemplateEntity>
     * @功能: 以模板id为key,以品牌列表为值;根据模板id为key,以规格选项为值放入redis中.
     **/
    @Override
    public List<TypeTemplateEntity> findAll() {
        List<TypeTemplateEntity> list = this.list();
        for (TypeTemplateEntity typeTemplateEntity : list) {

            // 1.1 得到品牌列表并转换为集合
            String brandIds = typeTemplateEntity.getBrandIds();
            List<Map> brandList = JSON.parseArray(brandIds, Map.class);
            System.out.println("brandList = " + brandList);
            //以模板id为key,以品牌列表为值;
            redisTemplate.boundHashOps("brandList").put(typeTemplateEntity.getId(),JSON.toJSONString(brandList));

            String specIds = typeTemplateEntity.getSpecIds();
            List<Map> maps = JSON.parseArray(specIds, Map.class);
            for (Map map : maps) {
                //1.2.1得到规格的id (spec_id)
                String id = map.get("id")+ "";
                //1.2.2 根据规格id查询规格选项列表
                List<SpecificationOptionEntity> options = optionService.list(new QueryWrapper<SpecificationOptionEntity>().eq("spec_id", id));
                //1.2.3 将options放入map中
                map.put("options",options);
            }
            //1.2.4 将上面的规格和规格选项放入redis中
            redisTemplate.boundHashOps("specList").put(typeTemplateEntity.getId(),JSON.toJSONString(maps));
        }

        return list;
    }

}